<template>
  <div class="container">
    <!-- <div class="title">参数管理</div> -->
    <a-layout>
      <a-layout-content style="margin-left: 10px">
        <div class="top">
          <a-row style="width: 100%">
            <a-col :span="21">
              <a-form ref="formRef" :model="form" auto-label-width>
                <a-row :gutter="20">
                  <a-col
                    v-for="(item, index) in columnData.filter(
                      (v) =>
                        (v.isSearch != false &&
                          typeof v.isSearch === 'boolean') ||
                        v.isSearch === undefined
                    )"
                    :key="index"
                    :span="8"
                  >
                    <a-form-item
                      v-if="item.type === undefined || item.type === 'input'"
                      :field="item.dataIndex"
                      :label="item.title + ':'"
                      label-col-flex="60px"
                    >
                      <a-input
                        v-model="form[item.dataIndex]"
                        allow-clear
                        :placeholder="'请输入' + item.title"
                      />
                    </a-form-item>

                    <a-form-item
                      v-if="item.type === 'rangePicker'"
                      :field="item.dataIndex"
                      :label="item.title + ':'"
                      label-col-flex="60px"
                    >
                      <a-range-picker
                        v-model="form[item.dataIndex]"
                        show-time
                        :time-picker-props="{
                          defaultValue: ['00:00:00', '00:00:00'],
                        }"
                      />
                    </a-form-item>

                    <a-form-item
                      v-if="item.type === 'select'"
                      :field="item.dataIndex"
                      :label="item.title + ':'"
                      label-col-flex="60px"
                    >
                      <div
                        :id="'searchSelectDIv' + item.dataIndex"
                        style="position: relative; width: 100%"
                      >
                        <a-select
                          v-model="form[item.dataIndex]"
                          :popup-container="'#searchSelectDIv' + item.dataIndex"
                          allow-clear
                          :placeholder="'请选择' + item.title"
                        >
                          <a-option
                            v-for="(op, idx) in item.selectOptions"
                            :key="idx"
                            :label="op[item.options?.label || 'label']"
                            :value="op[item.options?.value || 'value']"
                          ></a-option>
                        </a-select>
                      </div>
                    </a-form-item>

                    <a-form-item
                      v-if="item.type === 'treeSelect'"
                      :field="item.dataIndex"
                      :label="item.title + ':'"
                      label-col-flex="60px"
                    >
                      <div
                        :id="'searchTreeSelectDIv' + item.dataIndex"
                        style="position: relative; width: 100%"
                      >
                        <a-tree-select
                          v-model="form[item.dataIndex]"
                          :popup-container="
                            '#searchTreeSelectDIv' + item.dataIndex
                          "
                          :data="item.selectOptions"
                          :placeholder="'请选择' + item.title"
                          :field-names="item.options"
                        ></a-tree-select>
                      </div>
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-form>
            </a-col>

            <a-col :span="1" class="filter-line">
              <a-row align="center" justify="center">
                <div class="line"></div>
              </a-row>
            </a-col>

            <a-col :span="2">
              <a-space fill direction="vertical">
                <a-button type="primary" @click="searchHandler">
                  <template #icon>
                    <icon-search />
                  </template>
                  <!-- Use the default slot to avoid extra spaces -->
                  <template #default>搜索</template>
                </a-button>
                <a-button @click="resetForm">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  <!-- Use the default slot to avoid extra spaces -->
                  <template #default>重置</template>
                </a-button>
              </a-space>
            </a-col>
          </a-row>

          <!-- <a-button type="primary" @click="addClick('add', 1)">
            <template #icon>
              <icon-plus></icon-plus>
            </template>
            新增
          </a-button> -->

          <a-space fill>
            <a-button type="primary" @click="addClick('add', 1)">
              <template #icon>
                <icon-plus></icon-plus>
              </template>
              新增
            </a-button>

            <a-button type="primary" @click="deleteCheckbox">
              <template #icon>
                <icon-plus></icon-plus>
              </template>
              删除
            </a-button>
          </a-space>
        </div>
        <a-table
          :columns="
            columnData.filter(
              (v) =>
                (v.isTable != false && typeof v.isTable === 'boolean') ||
                v.isTable === undefined
            )
          "
          class="table"
          :scroll="scroll"
          row-key="id"
          :data="tableData"
          :hoverable="true"
          :bordered="false"
          :pagination="pagination"
          :row-selection="rowSelection"
          v-model:selectedKeys="selectedKeys"
          @page-change="pageChange"
          @page-size-change="pageSizeChange"
        >
          <template #num="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>

          <template #avatar="{ record }">
            <a-image
                width="100"
                :src="record.avatar"
            />
          </template>

          <template #componentCode="{ record }">
            <span
              style="color: rgb(64, 158, 255); cursor: pointer"
              @click="searchList(record)"
              >查看</span
            >
          </template>

          <template #operate="{ record }">
            <a-button type="text" @click="viewClick('view', 1, record)">
              <template #icon>
                <icon-eye />
              </template>

              <template #default>查看</template>
            </a-button>
            <a-button type="text" @click="addClick('edit', 1, record)">
              <template #icon>
                <icon-edit />
              </template>

              <template #default>编辑</template>
            </a-button>
            <a-button type="text" @click="deleteItem(record)">
              <template #icon>
                <icon-delete />
              </template>

              <template #default>删除</template>
            </a-button>
          </template>
        </a-table>
      </a-layout-content>
    </a-layout>

    <Add
      :show="modalData.show"
      :type="modalData.type"
      :data="modalData.data"
      :select-trader="selectTrader"
      @success="handleSuccess"
      @close="closeModal"
    >
    </Add>
    <View
      :visible="viewData.visible"
      :type="viewData.type"
      :data="viewData.data"
      @success="viewSuccess"
      @close="closeview"
    >
    </View>
  </div>
</template>

<script setup>
  import { ref, onMounted, getCurrentInstance, reactive } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { downloadFile } from '@/templateDir/utils/util';

  import { paginations } from '@/templateDir/utils/constant';
  import lodash from 'lodash';
  import { useUserStore } from '@/store';

  import {
    deleteDataReq,
    getDetailReq,
    getListReq,
    exportDataReq,
    columnData,
    initOtherData,
  } from './data';
  import Add from './add.vue';
  import View from './view.vue';

  const { proxy } = getCurrentInstance();

  const userState = useUserStore();

  const form = reactive({});

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });

  const selectedKeys = ref([]);

  const pagination = ref(lodash.cloneDeep(paginations));
  pagination.value.size = pagination.value.pageSize;

  const tableData = ref([]);

  const scroll = {
    x: 1200,
    y: 420,
  };

  const modalData = ref({
    show: false,
    type: '',
    data: {},
  });

  const transformDate = (obj) => {
    const dateObj = lodash.cloneDeep(obj);
    if (dateObj.createTime) {
      dateObj.queryStartDate = dateObj.createTime?.[0];
      dateObj.queryEndDate = dateObj.createTime?.[1];
      delete dateObj.createTime;
    }
    return dateObj;
  };

  const viewData = ref({
    visible: false,
    type: '',
    data: columnData.value.filter(
      (v) =>
        (v.isView !== false && typeof v.isView === 'boolean') ||
        v.isView === undefined
    ),
  });

  const itemInfoColumns = [
    {
      title: '序号',
      dataIndex: 'number',
    },
    {
      title: 'SN编码',
      dataIndex: 'sn',
    },
  ];

  const itemInfo = ref([]);
  const isShowItem = ref(false);

  const searchList = (obj) => {
    obj.storeExcels.forEach((v, i) => {
      v.number = i + 1;
    });

    itemInfo.value = obj.storeExcels;

    isShowItem.value = true;
  };

  const exportHandler = async () => {
    const data = {
      current: pagination.value.current,
      size: pagination.value.size,
      tenantId: userState.tenantId,
      ...transformDate(form),
    };
    const res = await exportDataReq(data);
    downloadFile(res);
  };

  const getTableData = async (params = {}) => {
    const data = {
      current: pagination.value.current,
      size: pagination.value.size,
      ...params,
      ...transformDate(form),
      tenantId: userState.tenantId,
    };
    const res = await getListReq(data);
    tableData.value = res?.data?.records;
    pagination.value.total = res?.data?.total;
  };

  const resetForm = () => {
    pagination.value.current = 1;
    proxy.$refs.formRef.resetFields();
    getTableData();
  };

  const searchHandler = () => {
    pagination.value.current = 1;
    getTableData();
  };

  const viewClick = (type, idx, data = {}) => {
    viewData.value.visible = true;
    viewData.value.type = type;
    viewData.value.data.forEach((v) => {
      if (v.selectOptions) {
        v.value = v.renderView(data[v.dataIndex]);
      } else {
        v.value = data[v.dataIndex];
      }
    });
  };

  const addClick = (type, idx, data = {}) => {
    if (type === 'edit') {
      getDetailReq(data.id).then((res) => {
        modalData.value.show = true;
        modalData.value.type = type;
        modalData.value.data = { ...res.data };
      });
    } else {
      modalData.value.show = true;
      modalData.value.type = type;
      modalData.value.data = {};
    }
  };

  const selectTrader = ref([]);

  const closeModal = () => {
    modalData.value.show = false;
  };
  const closeview = () => {
    viewData.value.visible = false;
  };

  const viewSuccess = () => {
    viewData.value.visible = false;
    pagination.value.current = 1;
    pagination.value.size = 10;
    getTableData();
  };

  const handleSuccess = () => {
    modalData.value.show = false;
    pagination.value.current = 1;
    pagination.value.size = 10;
    getTableData();
  };

  const deleteCheckbox = () => {
    console.log(selectedKeys.value);
    if (selectedKeys.value.length > 0) {
      proxy
        .$confirmModal({
          content: '',
        })
        .then(async () => {
          const res = await deleteDataReq(selectedKeys.value.join(','));
          if (res && res.code === 200) {
            Message.success('删除成功');
            getTableData();
          }
        });
    }
  };

  const deleteItem = (row) => {
    proxy
      .$confirmModal({
        content: row.name,
      })
      .then(async () => {
        const res = await deleteDataReq(row.id);
        if (res && res.code === 200) {
          Message.success('删除成功');
          getTableData();
        }
      });
  };
  const pageChange = (v) => {
    pagination.value.current = v;
    getTableData();
  };
  const pageSizeChange = (v) => {
    pagination.value.size = v;
    getTableData();
  };

  onMounted(() => {
    getTableData();
    initOtherData();
  });
</script>

<style lang="less" src="./index.less" scoped></style>
@/templateDir/utils/util@/templateDir/utils/constant